package com.wjk.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import java.util.Scanner;

/**
 * @author: RobertWei
 * time: 2021/8/14    10:59
 * @TODO:
 */

public class AuthenticationDemo {
    public static void main(String[] args) {

        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");

        SecurityManager securityManager = factory.getInstance();

        SecurityUtils.setSecurityManager(securityManager);

        Subject subject = SecurityUtils.getSubject();

        Scanner scanner = new Scanner(System.in);

        System.out.println("请输入用户名");

        String username = scanner.nextLine();

        System.out.println("请输入密码");

        String password = scanner.nextLine();

        UsernamePasswordToken token = new UsernamePasswordToken(username,password);


        try {
            subject.login(token);
            System.out.println("认证成功");
        } catch (AuthenticationException e) {
            System.out.println("认证失败"+e.getMessage());
        }


        /**
         * 是  认证方法返回的第一个参数
         */

        PrincipalCollection principals = subject.getPrincipals();
        System.out.println("principals = " + principals);


        //user 存到session

        //授权
        boolean permitted = subject.isPermitted("class:info");
        System.out.println("permitted = " + permitted);

        boolean isA = subject.isPermitted("admin:a");

        System.out.println("isA = " + isA);


        boolean isSuper = subject.hasRole("super");

        System.out.println("isSuper = " + isSuper);


    }
}
